import User from "./User";

class Test {
    public count = 0;
    constructor() {
        this.init();
    }

    private init() {
        console.log("init");

        new User();
        let _this = this;
        document.addEventListener("click", function () {
            _this.count++;
            if (_this.count % 2 == 0) {
                _this.show("1");
            } else {
                _this.show("2");
            }
        });

        let type = this.getQueryString("type");
        this.show(type);

    }

    private show(type: String) {
        let xml = new XMLHttpRequest();
        let _this = this;
        switch (type) {
            case "1":
                xml.open("get", "testB.js");
                xml.onload = function (e) {
                    _this.loadScript(xml.responseText+ '\n//@ sourceURL=testB');
                    let cModule = __webpack_require__('./src/b/TestB.ts');
                    new cModule.default();
                };
                xml.send();
                break;
            case "2":
                xml.open("get", "testC.js");
                xml.onload = function (e) {
                    _this.loadScript(xml.responseText+ '\n//@ sourceURL=testC');
                    let cModule = __webpack_require__('./src/c/TestC.ts');
                    new cModule.default();
                };
                xml.send();
                break;
        }
    }

    /**
     * 获得URL参数值
     * @param	name 参数名称
     * @return	参数值
     */
    public getQueryString(name:string):string {
        if(!window.location || !window.location.search)
            return null;
        let reg:RegExp = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    public loadScript(str:string):void {
        let script = document.createElement('script');
        script.type = "text/javascript";
        script.text = str;
        document.head.appendChild(script);
        document.head.removeChild(document.head.lastChild);
    }

}

new Test();